package com.xiaoyang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoyang.common.BaseContext;
import com.xiaoyang.common.CustomException;
import com.xiaoyang.domain.Category;
import com.xiaoyang.domain.Dish;
import com.xiaoyang.domain.Setmeal;
import com.xiaoyang.mapper.CategoryMapper;
import com.xiaoyang.service.CategoryService;
import com.xiaoyang.service.DishService;
import com.xiaoyang.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @auther XiaoYang
 * @DATE 2022/12/11-18:59
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id删除分类，删除之前进行判断
     * @param id
     */
    @Override
    public void remove(Long id) {
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件(根据分类id查询)
        dishQueryWrapper.eq(Dish::getCategoryId,id);

        //查询当前分类是否关联了菜品，如果已经关联，直接抛业务异常
        int dishCount = dishService.count(dishQueryWrapper);
        if (dishCount > 0){
            //已经关联菜品，直接抛业务异常
            throw  new CustomException("当前分类下关联了菜品，不能删除");
        }

        LambdaQueryWrapper<Setmeal> setmealQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件(根据分类id查询)
        setmealQueryWrapper.eq(Setmeal::getCategoryId,id);
        //查询当前分类是否关联了套餐，如果已经关联，直接抛业务异常
        int setmealCount = setmealService.count(setmealQueryWrapper);
        if (setmealCount > 0){
            //已经关联套餐，直接抛业务异常
            throw  new CustomException("当前分类下关联了套餐，不能删除");
        }
        //正常删除分类
        super.removeById(id);
        BaseContext.close();
    }
}
